<?php
namespace app\channel\controller;
use think\Db;

class RebateOrder extends Base
{
    public function index(){
        if(request()->isAjax() || input('?export')){
            $page = input('page');
            $limit = input('limit');
            $date = explodeTime(input('date'));
            $roleId = input('role_id');
            $myOrderId = input('my_order_id');
            $payOrderId = input('pay_order_id');
            $gameId = input('game_id');
            $plat = input('plat');

            $where = "order_time between '{$date['start_time']}' AND '{$date['end_time']}' && debug=0 && pay_result=1 && game_result=1";

            if($plat == 'cps'){
                if( session('admin.cps_id') ){
                    $allChannelId = model('manage/Channel')->allChannelId( session('admin.cps_id') );
                    $where .= " && channel_id=1000 && reg_cps_id in ({$allChannelId})";
                }else{
                    $this->layTable(0, '', [], 0);
                }
            }
            if($plat == 'sdk'){
                if( session('admin.sdk_id') ){
                    $where .= " && channel_id=".session('admin.sdk_id');
                }else{
                    $this->layTable(0, '', [], 0);
                }
            }
            !empty($roleId) && $where .= " && (role_id='{$roleId}' OR role_name like '%{$roleId}%')";
            !empty($myOrderId) && $where .= " && my_order_id='{$myOrderId}'";
            !empty($payOrderId) && $where .= " && pay_order_id='{$payOrderId}'";
            !empty($gameId) && $where .= " && game_id='{$gameId}'";

            $start = ($page-1)*$limit;
            $length = $limit;

            $y1 = date('Y', $date['start_time']);
            $y2 = date('Y', $date['end_time']);

            if($y1 == $y2){ //同一年
                $count = Db::name('PayOrderY_'.$y1)->where($where)->count();

                if(!$count){
                    $this->layTable(0, '', [], 0);
                }

                $select = Db::name('PayOrderY_'.$y1)
                    ->where($where)
                    ->limit($start, $length)
                    ->order('order_time desc')
                    ->select();

                $sum = Db::name('PayOrderY_'.$y1)
                    ->where($where)
                    ->sum('total_price');
            }else{ //跨年
                $field = "order_time, channel_id, reg_cps_id, game_id, my_user_id, my_user_name, role_id, role_name, server_id, server_name, my_order_id, pay_order_id, total_price, pay_type, pay_time";
                $subQuery = Db::name('PayOrderY_'.$y1)
                    ->field($field)
                    ->where($where)
                    ->union("select {$field} from sdk_pay_order_y_{$y2} where ({$where})", true)
                    ->buildSql();

                $count = Db::table($subQuery.' y')->count();

                if(!$count){
                    $this->layTable(0, '', [], 0);
                }

                $select = Db::table($subQuery.' y')
                    ->limit($start, $length)
                    ->order('order_time desc')
                    ->select();

                $sum = Db::table($subQuery.' y')
                    ->sum('total_price');
            }

            $gameIdName = model('manage/Game')->gameIdName();
            $channelIdName = model('manage/Channel')->channelIdName();

            $data = [];
            foreach ($select as $k=>$v){
                unset($whereApply);
                session('admin.cps_id') && $whereApply['cps_id'] = session('admin.cps_id');
                session('admin.sdk_id') && $whereApply['channel_id'] = session('admin.sdk_id');
                $whereApply['game_id'] = $v['game_id'];
                $whereApply['role_name'] = $v['role_name'];
                $whereApply['status'] = ['<>', 3];
                $whereApply[] = ['exp', "FIND_IN_SET('{$v['my_order_id']}', pay_id)"];
                $apply = Db::name('ChannelRebate')->where($whereApply)->count();

                $data[] = [
                    'order_time' => date('Y-m-d H:i:s', $v['order_time']),
                    'reg_cps_id' => $v['channel_id']==1000 ? $v['reg_cps_id'] : $v['channel_id'],
                    'reg_cps_name' => $v['channel_id']==1000 ? $channelIdName[ $v['reg_cps_id'] ] : $channelIdName[ $v['channel_id'] ],
                    'game_id' => $v['game_id'],
                    'game_name' => $gameIdName[ $v['game_id'] ],
                    'my_user_id' => $v['my_user_id'],
                    'my_user_name' => $v['my_user_name'],
                    'role_id' => $v['role_id'],
                    'role_name' => $v['role_name'],
                    'server_id' => $v['server_id'],
                    'server_name' => $v['server_name'],
                    'my_order_id' => $v['my_order_id'],
                    'pay_order_id' => $v['pay_order_id'],
                    'total_price' => '¥ ' . $v['total_price']/100,
                    'pay_time' => $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '',
                    'apply' => $apply ? 1 : 0,
                ];
            }

            $this->layTable(0, '支付订单', $data, $count, round($sum/100, 2));
        }else{
            $date = date('Y-m-d', time()).' - '.date('Y-m-d', time());
            $channelData = model('Base')->channelNotice();
            $gameData = model('Base')->gameNotice();

            if(session('admin.cps_id') && session('admin.sdk_id')){
                $cpsSelected = 'selected';
                $sdkSelected = '';
            }else if(session('admin.cps_id')){
                $cpsSelected = 'selected';
                $sdkSelected = '';
            }else if(session('admin.sdk_id')){
                $cpsSelected = '';
                $sdkSelected = 'selected';
            }
            return view('', ['date'=>$date, 'channel_data'=>$channelData, 'game_data'=>$gameData, 'cps_selected'=>$cpsSelected, 'sdk_selected'=>$sdkSelected]);
        }
    }

    public function rebate(){
        $myOrderId = input('my_order_id');
        $arr = explode(',', $myOrderId);
        $str = '';
        foreach ($arr as $v) {
            $str .= "'".$v."',";
        }
        $str = rtrim($str, ',');

        $plat = input('plat');

        $where = "my_order_id in ({$str})";
        if($plat == 'cps'){
            $allChannelId = model('manage/Channel')->allChannelId( session('admin.cps_id') );
            $where .= " && channel_id=1000 && reg_cps_id in ({$allChannelId})";
            $id = session('admin.cps_id');
        }else{
            $where .= " && channel_id=".session('admin.sdk_id');
            $id = session('admin.sdk_id');
        }

        $table = get_order_table($arr[0]);
        $order = Db::name($table)->field('channel_id,reg_cps_id,game_id,server_name,role_name,role_id,total_price,pay_time,my_order_id')->where($where)->select();

        $myOrderIdBack = [];
        if(count($order)==1){
            session('admin.cps_id') && $whereApply['cps_id'] = session('admin.cps_id');
            session('admin.sdk_id') && $whereApply['channel_id'] = session('admin.sdk_id');
            $whereApply['game_id'] = $order[0]['game_id'];
            $whereApply['role_name'] = $order[0]['role_name'];
            $whereApply['status'] = ['<>', 3];
            $whereApply[] = ['exp', "FIND_IN_SET('{$order[0]['my_order_id']}', pay_id)"];
            $apply = Db::name('ChannelRebate')->where($whereApply)->count();
            $apply && $this->layJson(1, '您已经申请过该订单返利');

            Db::name('ChannelRebate')->insert([
                'cps_id' => session('admin.cps_id'),
                'channel_id' => session('admin.sdk_id'),
                'game_id' => $order[0]['game_id'],
                'server_name' => $order[0]['server_name'],
                'role_name' => $order[0]['role_name'],
                'role_id' => $order[0]['role_id'],
                'pay_money' => $order[0]['total_price']/100,
                'pay_time' => $order[0]['pay_time'],
                'pay_id' => $order[0]['my_order_id'],
                'apply_time' => time(),
                'status' => 0,
                'remark' => input('remark')
            ]);
            $myOrderIdBack[] = $order[0]['my_order_id'];
        }else{
            foreach($order as $k=>$v){
                unset($whereApply);
                session('admin.cps_id') && $whereApply['cps_id'] = session('admin.cps_id');
                session('admin.sdk_id') && $whereApply['channel_id'] = session('admin.sdk_id');
                $whereApply['game_id'] = $v['game_id'];
                $whereApply['role_name'] = $v['role_name'];
                $whereApply['status'] = ['<>', 3];
                $whereApply[] = ['exp', "FIND_IN_SET('{$v['my_order_id']}', pay_id)"];
                $apply = Db::name('ChannelRebate')->where($whereApply)->count();
                if($apply) continue;

                if(!isset($item[$id][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])])){
                    $item[$id][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])]=$v;
                }else{
                    $item[$id][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])]['total_price'] += $v['total_price'];
                    $item[$id][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])]['my_order_id'] .= ','.$v['my_order_id'];
                }
                $myOrderIdBack[] = $v['my_order_id'];
            }

            $insert = [];
            foreach ($item as $channelId=>$v){
                foreach ($v as $gameId=>$vv){
                    foreach ($vv as $serverName=>$vvv){
                        foreach ($vvv as $roleName=>$vvvv){
                            foreach ($vvvv as $payTime=>$vvvvv){
                                $insert[] = [
                                    'cps_id' => session('admin.cps_id'),
                                    'channel_id' => session('admin.sdk_id'),
                                    'game_id' => $vvvvv['game_id'],
                                    'server_name' => $vvvvv['server_name'],
                                    'role_name' => $vvvvv['role_name'],
                                    'role_id' => $vvvvv['role_id'],
                                    'pay_money' =>  $vvvvv['total_price']/100,
                                    'pay_time' =>  $vvvvv['pay_time'],
                                    'pay_id' =>  $vvvvv['my_order_id'],
                                    'apply_time' => time(),
                                    'status' => 0,
                                    'remark' => input('remark'),
                                ];
                            }
                        }
                    }
                }
            }

            Db::name('ChannelRebate')->insertAll($insert);
        }

        if($myOrderIdBack){
            $this->layJson(0, '申请返利成功', $myOrderIdBack);
        }else{
            $this->layJson(1, '申请返利失败，请刷新重试');
        }
    }

}
